package com.gitee.ricesugar.service.impl;

import cn.hutool.core.util.IdUtil;
import com.gitee.ricesugar.controller.dto.LoginDTO;
import com.gitee.ricesugar.controller.request.LoginRequest;
import com.gitee.ricesugar.entity.Admin;
import com.gitee.ricesugar.entity.User;
import com.gitee.ricesugar.exception.ServiceException;
import com.gitee.ricesugar.mapper.AdminMapper;
import com.gitee.ricesugar.mapper.UserMapper;
import com.gitee.ricesugar.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class LoginService implements ILoginService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    public LoginDTO login(LoginRequest request) {
        LoginDTO loginDTO;
        Admin admin = adminMapper.getByUsernameAndPassword(request);
        User user = userMapper.getByUsernameAndPassword(request);
        if (admin == null && user == null) {
            throw new ServiceException("用户名或密码错误");
        }
        loginDTO = new LoginDTO();
        if (admin != null) {
            loginDTO.setIsAdmin(true);
            BeanUtils.copyProperties(admin, loginDTO);
        } else {
            loginDTO.setIsAdmin(false);
            BeanUtils.copyProperties(user, loginDTO);
        }
        return loginDTO;
    }

    @Override
    public void add(User obj) {
        List<User> users = userMapper.listByUsername(obj.getUsername());
        List<Admin> admins = adminMapper.listByUsername(obj.getUsername());
        if (!users.isEmpty() || !admins.isEmpty()) {
            throw new ServiceException("用户名已存在");
        }
        int uid = Math.abs(IdUtil.fastSimpleUUID().hashCode());
        obj.setUid(Integer.toString(uid));
        userMapper.add(obj);
    }
}
